<template>
    <view class="container paddingBottomBar" :style="themeColor">
        <header-bar :config="config"></header-bar>
        <view class="search-bar-box">
            <search-bar placeholderText="输入搜索的商品名称" :autoFocus="true" ref="searchBar" :lightStyle="true"
                :showSearchBtn="false" :actions="actions" @actionFn="actionFn"></search-bar>
        </view>
        <view class="main">
            <view v-if="showResult" class="reuslt">
                <view v-if="productType == 4">
                    <product-list-group v-if="loadOk" ref="swiperIndex" @sku="sku" :requestData="requestData" isClass
                        :displayData="displayData" :height="listHeight" :infoType="4" isSearch>
                    </product-list-group>
                </view>
                <view v-else>
                    <product-list v-if="loadOk" ref="swiperIndex" :productType="productType" @sku="sku"
                        @amountProp="amountProp" :requestData="requestData" isClass :displayData="displayData"
                        :height="listHeight" :infoType="'0'" isSearch>
                    </product-list>
                </view>
            </view>
            <view v-else class="search-point">
                <view class="search-point-item" v-if="hotKeys && hotKeys.length > 0">
                    <view class="search-point-item-title">
                        <text class="title-text">热门搜索</text>
                    </view>
                    <view class="key-items">
                        <text class="key-item" v-for="(item, index) in hotKeys" :key="index">{{ item }}</text>
                    </view>
                </view>
                <view class="search-point-item">
                    <view class="search-point-item-title">
                        <text class="title-text">最近搜索</text>
                        <iconsfont customIcons="icon-shanchu" class="icon-del" :color="'#666666'" size="30"
                            @click="clearFn"></iconsfont>
                    </view>
                    <view class="key-items" v-if="historyKeys && historyKeys.length > 0">
                        <text class="key-item" v-for="(item, index) in historyKeys" :key="index"
                            @click="useKeyFn(item)">{{ item }}</text>
                    </view>
                    <view v-else>
                        <text class="empty-text">暂无搜索内容</text>
                    </view>
                </view>
            </view>
        </view>
        <uni-popup type="bottom" ref="popSku" @change="skuChange" v-if="!getAppSet().pagesClassify">
            <product-spec v-if="showPopSku" :data="optPopup.data" :fresh="optPopup.change" :popup-type="optPopup.type"
                :orderType="orderType" :skuImg="optPopup.skuImg" @closePopup="closePopup" @addCart="addCart"
                :tempType="0" @addBatch="addBatch" @setCarListFunc="setCarListFunc"
                @specTreeClickEvent="specTreeClickEvent">
            </product-spec>
        </uni-popup>
        <uni-popup type="bottom" ref="popSku" @change="skuChange" v-else>
            <product-class-spec v-if="showPopSku" :data="optPopup.data" :fresh="optPopup.change"
                :popup-type="optPopup.type" @changeProductData="changeProductData" @closePopup="closePopup"
                @addCart="addCart" :tempType="0" @addBatch="addBatch" @setCarListFunc="setCarListFunc">
            </product-class-spec>
        </uni-popup>
        <uni-popup ref="popAmountTip" type="center" class="popAmountTip" :animation="false" :maskClick="true">
            <view class="pop-return-box">
                <view class="pop-return-title">
                    <text>输入订购数量</text>
                </view>
                <!-- #ifdef APP -->
                <input confirm-type="search" :auto-focus="true" maxlength="10" type="digit" v-model="popinputAmount"
                    class="btn-input" />
                <!-- #endif -->
                <!-- #ifndef APP -->
                <input confirm-type="search" :focus="isFocus" maxlength="10" :selection-start="selectionStart"
                    :selection-end="selectionEnd" type="digit" v-model="popinputAmount" class="btn-input" />
                <!-- #endif -->

                <view class="pop-action">
                    <view @click="popAmountClose">取消</view>
                    <view @click="popAmountConfirm">确定</view>
                </view>
            </view>
        </uni-popup>
        <view class="bottom-bar" v-if="showResult">
            <view class="go-cart-bar" v-if="total">
                <view class="go-cart-bar-left">
                    <view>
                        <text class="total-text-label">合计：</text>
                        <text class="total-text-price">{{ total.totalPrice }}</text>
                        <text class="total-text-price-unit">元</text>
                    </view>
                    <text class="total-amount-text">共{{ total.totalSpace }}种商品</text>
                </view>
                <view class="go-cart-bar-right">
                    <view class="btn-cart" @click="goCart">
                        <view class="cart-num">
                            <iconsfont customIcons="icon-gouwuche1" :color="'#ffffff'" size="30"></iconsfont>
                        </view>
                        <text class="cart-text">购物车</text>
                    </view>
                </view>
            </view>
        </view>
        <show-modal></show-modal>
    </view>
</template>
<script>
import searchBar from "@/components/common/search-bar.vue"
import { getElementHeight } from "@/uni-sub-base/utils/elementUtil.js"
import storage from "@/uni-sub-base/utils/storage.js"
import productList from "@/components/product/product-list.vue"
import productListGroup from "@/components/group/product-list.vue"
import productSpec from "@/components/product/product-spec.vue"
import productClassSpec from "@/components/productClass/product-spec.vue"
import { getProductDisplay } from "@/utils/appInit.js"
import { getCartTotal, getUserCarList } from "@/utils/cartUtil.js"
import { eventBus } from "@/utils/eventBus.js"
import utilsOld from "@/utils/utilsOld.js"
import { updateCart } from "@/utils/cartUtil.js"
export default {
    components: {
        searchBar,
        productList,
        productListGroup,
        productSpec,
        productClassSpec,
    },
    data() {
        return {
            config: {
                title: "搜索",
                back: true,
                color: ["#ffffff"],
                centerSlot: true,
                barPlaceholder: true,
            },
            loadOk: false,
            listHeight: "",
            showResult: false,
            historyKeys: [],
            hotKeys: [],
            actions: [
                {
                    type: "搜索",
                    id: 1,
                    isTextType: true,
                    iconType: 0,
                },
            ],
            requestData: {
                ProductType: 1,
                infoType: 0,
                isPromotion: false,
                search: "",
            },
            displayData: {},
            showPopSku: false, // 规格弹窗
            // sku 商品规格弹窗
            optPopup: {
                data: {},
                type: "",
                change: false,
                show: true,
                skuImg: "",
            },
            total: null,
            popTop: "",
            popite: {},
            popitem: {},
            popinputAmount: null,
            popstock: null,
            poptype: null,
            popminNum: null,
            popUnitRatio: null,
            popLimitBuy: null,
            popaddNum: null,
            ProductName: "",
            poprefresh: false,
            isFocus: false,
            selectionStart: -1,
            selectionEnd: 0,
            addNum: 1,
            productType: 1,
            orderType: -1,
        }
    },
    created() {
        this.config.backgroundColor = [1, this.getThemeColor]
    },
    mounted() {
        this.getHistoryKeys()
        this.GetProductDisplay()
        this.getListHeight()

        // if(this.productType==4){
        // 	getUserCarList(true,23).then(res => {})
        // }
        eventBus.$on("SET_CART", (msg) => {
            if (msg) {
                this.getCartNum(msg)
            }
        })
    },
    onLoad(e) {
        if (e.productType) {
            this.productType = +e.productType
            if (this.productType == 4) {
                this.requestData.ProductType = this.productType
                this.orderType = 23
            }
        }
    },
    methods: {
        changeProductData(product) {
            this.optPopup.data = product
            this.optPopup.change = true
        },
        amountProp(ite, item, type, displayData) {
            this.popite = ite
            this.popitem = item
            this.poptype = type
            this.popdisplayData = displayData
            if (ite.Amount == 0) {
                this.popinputAmount = 0
            } else {
                this.popinputAmount = ite.Amount
            }
            this.$refs.popAmountTip.open()
            setTimeout((e) => {
                this.isFocus = true
                this.selectionStart = 0
                this.selectionEnd = this.popinputAmount.toString().length
            }, 100)
        },
        blurFn() {
            this.$nextTick(() => {
                this.isFocus = false
                this.selectionStart = -1
                this.selectionEnd = -1
            })
        },
        popAmountClose() {
            this.$refs.popAmountTip.close()
            this.blurFn()
        },
        popAmountConfirm() {
            if (this.popite.Ratio == 1 && (this.popitem.ProductSkuList[0].AddNum > 0 ? this.popitem.ProductSkuList[0].AddNum : this.popitem.AddNum) > 0) {
                if (this.isInteger(this.popinputAmount, this.popitem.ProductSkuList[0].AddNum > 0 ? this.popitem.ProductSkuList[0].AddNum : this.popitem.AddNum)) {
                    this.inputAmount = this.popinputAmount
                    this.popite.Amount = this.popinputAmount
                    this.changeAmountFn(this.popite, this.popitem, this.poptype, this.popdisplayData)
                } else {
                    this.easyToast("请输入" + (this.popitem.ProductSkuList[0].AddNum > 0 ? this.popitem.ProductSkuList[0].AddNum : this.popitem.AddNum) + "的倍数")
                }
            } else {
                this.inputAmount = this.popinputAmount
                this.popite.Amount = this.popinputAmount
                this.changeAmountFn(this.popite, this.popitem, this.poptype, this.popdisplayData)
            }
        },
        changeAmountFn(item, ite, type, popdisplayData) {
            var that = this
            let num = item.Amount
            let stock = item.Stock
            let UnitRatio = item.Ratio
            let minNum = 0
            let addNum = 1
            let LimitBuy = 0
            if (ite.ProductSkuList[0].MinimumOrder > 0) {
                minNum = ite.ProductSkuList[0].MinimumOrder
            } else {
                minNum = ite.MinNum
            }
            if (ite.ProductSkuList[0].AddNum > 0) {
                addNum = ite.ProductSkuList[0].AddNum
            } else {
                addNum = item.Ratio && UnitRatio == 1 ? ite.AddNum : 1
            }
            if (ite.ProductSkuList[0].LimitBuy > 0) {
                LimitBuy = ite.ProductSkuList[0].LimitBuy
            } else {
                LimitBuy = ite.LimitBuy
            }
            const _oldAmount = item.Amount

            if (popdisplayData.NoCheckStock) {
                if (type != 0) {
                    item.Amount = num + Number(type)
                } else {
                    item.Amount = num
                }
                if (item.Amount < 0) {
                    item.Amount = 0
                }
            } else {
                utilsOld.changeAmountNew(item, num, stock, type, minNum, UnitRatio, LimitBuy, addNum)
            }
            this.poprefresh = true
            this.$nextTick(() => {
                this.poprefresh = false
            })
            this.$forceUpdate()
            //商品
            if (_oldAmount !== item.Amount || type === 0) {
                const _obj = {}
                _obj.ProductId = item.ProductId
                _obj.Amount = item.Amount
                _obj.SkuId = item.SkuId
                _obj.UnitId = item.UnitId
                _obj.UnitName = item.UnitName
                _obj.Ratio = item.Ratio
                let param = []
                param.push(_obj)
                updateCart(param, false, true).then((res) => { })
            }
            setTimeout((e) => {
                that.$refs.popAmountTip.close()
                this.blurFn()
            }, 500)
        },
        //获取购物车总数
        getCartNum(cartData) {
            getCartTotal(cartData, (res) => {
                this.total = res
            })
        },
        getHistoryKeys() {
            let historyKeys = storage.getCache("historyKeys")
            if (historyKeys && historyKeys.length > 0) {
                this.historyKeys = historyKeys
            } else {
                this.historyKeys = []
            }
        },
        getListHeight() {
            //获取商品高度
            getElementHeight(this, ".main", (e) => {
                this.listHeight = e - 65 + "px"
                this.loadOk = true
            })
        },
        checkIsIn(key, keys) {
            let result = keys.find((e) => {
                return e == key
            })
            return result
        },
        actionFn(e) {
            if (e.id == 1) {
                //搜索
                let key = this.$refs.searchBar.getValue()
                if (key) {
                    let keys = storage.getCache("historyKeys")
                    if (!keys) {
                        keys = []
                    } else if (this.checkIsIn(key, keys)) {
                        //TODO 存在相同
                        keys = keys.filter((e) => {
                            return e != key
                        })
                    } else if (keys.length >= this.getAppSet().searchHistoryMax) {
                        keys.pop()
                    }

                    keys.unshift(key)
                    storage.setCache("historyKeys", keys)
                    this.showResult = true
                    //搜索商品
                    this.requestData.search = key
                    setTimeout((e) => {
                        if (this.$refs.swiperIndex) {
                            this.$refs.swiperIndex.refresh(this.requestData)
                        }
                    }, 500)
                } else {
                    this.requestData.search = ""
                    this.getHistoryKeys()
                    this.showResult = false
                }
            }
        },
        clearFn() {
            storage.removeCache("historyKeys")
            this.getHistoryKeys()
        },
        // 获取整体显示设置
        GetProductDisplay() {
            getProductDisplay().then((res) => {
                if (res) {
                    this.displayData = res.Data
                }
            })
        },
        useKeyFn(key) {
            this.$refs.searchBar.setValue(key)
        },
        skuChange(e) {
            if (!e.show) {
                this.showPopSku = false
            }
        },
        sku(item) {
            this.showPopSku = true
            this.optPopup.type = "attr"
            this.optPopup.data = item
            console.log("item")
            console.log(item)
            // 默认选中第一个规格，显示对应规格图片
            let ProductSkuAttrList = item.ProductUnitList?.[0]?.ProductSkuAttrList;
            let SkuId = "";
            if (ProductSkuAttrList && ProductSkuAttrList.length) {
                let ProductAttrList = ProductSkuAttrList[0].ProductAttrList;
                if (ProductAttrList && ProductAttrList.length) {
                    ProductAttrList.forEach((pItem, index) => {
                        if (index == 0) {
                            SkuId = pItem.SkuModel.SkuId
                            this.optPopup.skuImg = pItem.SkuModel.SkuImg
                        }
                    })
                }
            }
            this.$refs.popSku.open()
        },
        closePopup() {
            this.$refs.popSku.close()
        },
        addCart(e) {
            this.$refs.popSku.close()
        },
        addBatch(e) {
            this.$refs.popSku.close()
            this.$refs.popBatch.open()
        },
        specTreeClickEvent(item, index) {
            let skuId = "";
            // 找到对应品名skuid
            if (item.ProductAttrList && item.ProductAttrList.length > 0) {
                item.ProductAttrList.forEach((e, index) => {
                    if (index == 0) {
                        skuId = e.SkuId
                        this.optPopup.skuImg = e.SkuImg = e.SkuModel.SkuImg
                    }

                })
            }
        },
        goCart() {
            if (this.getSupplierMode() == 0) {
                if (this.productType == 4) {
                    this.easyGoTo("/pages/group/cart/index")
                } else {
                    this.easyGoTo("/pages/cart/cartTemp")
                }
            } else if (this.getSupplierMode() == 1) {
                this.easyGoTo("/pages/supplier/cart/cartTemp")
            }
        },
    },
}
</script>

<style lang="scss">
page {
    background: $color-white;
}

.search-point {
    display: flex;
    flex-direction: column;

    .search-point-item {
        display: flex;
        flex-direction: column;
        padding: $app-page-padding;

        .search-point-item-title {
            display: flex;
            flex-direction: row;
            align-items: center;
            margin-bottom: 24rpx;

            .title-text {
                flex: 1;
                font-size: $font-size-28;
                font-weight: bold;
            }
        }

        .key-items {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;

            .key-item {
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: $font-size-28;
                margin-bottom: $app-page-padding;
                margin-right: $app-page-padding;
                padding: 12rpx 24rpx;
                border-radius: 60rpx;
                background: #f8f8f8;
            }
        }
    }

    .empty-text {
        color: $app-color-text-tip;
    }
}

.reuslt {
    background: $uni-bg-color-grey;
}

.bottom-bar {
    justify-content: flex-start;
}

.go-cart-bar {
    display: flex;
    flex-direction: row;
    flex: 1;

    .go-cart-bar-left {
        display: flex;
        flex-direction: column;
        flex: 1;

        .total-text-label {
            font-size: $font-size-24;
        }

        .total-text-price {
            font-size: $font-size-36;
            color: $app-color-main;
            margin-right: 4rpx;
        }

        .total-text-price-unit {
            font-size: $font-size-28;
        }
    }

    .total-amount-text {
        color: $app-color-text-tip;
    }

    .btn-cart {
        width: 272rpx;
        background: $app-color-main;
        height: 80rpx;
        border-radius: 80rpx;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;

        .cart-num {
            padding-bottom: 6rpx;
        }

        .cart-text {
            margin-left: 12rpx;
            color: $color-white;
        }
    }
}
</style>
